#!/bin/sh
set -xe
PICTURES_DIR="$HOME/Pictures"
TMP_FILE="/tmp/bing_$(date +%Y%m%d).tmp"
HASH_CMD="sha256sum"
XBGCLIP_CMD="xbgclip"

mkdir -p "$PICTURES_DIR"

# 修复curl选项，去掉冲突的-O，保留-L跟随重定向
curl -s -L --output "$TMP_FILE" https://bing.img.run/uhd.php || {
    echo "curl下载失败"
    exit 1
}

[ ! -f "$TMP_FILE" ] && { echo "临时文件未创建"; exit 1; }

FILE_HASH=$($HASH_CMD "$TMP_FILE" | awk '{print $1}')

EXISTING_FILE=$(find "$PICTURES_DIR" -maxdepth 1 -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.gif" -o -iname "*.bmp" -o -iname "*.webp" -o -iname "*.svg" \) -exec $HASH_CMD {} \; | awk -v hash="$FILE_HASH" '$1 == hash {print $2}' | head -n 1)

if [ -z "$EXISTING_FILE" ]; then
    FILENAME=$(basename "$(curl -sI https://bing.img.run/uhd.php | grep -i 'Content-Disposition' | sed -n 's/.*filename="\(.*\)".*/\1/p')")
    [ -z "$FILENAME" ] && FILENAME="bing_$(date +%Y%m%d).jpg"
    DEST_PATH="$PICTURES_DIR/$FILENAME"
    mv "$TMP_FILE" "$DEST_PATH"
    SELECTED_IMAGE="$DEST_PATH"
else
    SELECTED_IMAGE="$EXISTING_FILE"
    rm "$TMP_FILE"
fi

command -v xclip >/dev/null 2>&1 && printf "%s" "$SELECTED_IMAGE" | xclip -sel clip

printf "%s" "$SELECTED_IMAGE" | "$XBGCLIP_CMD"
exit_code=$?

command -v notify-send >/dev/null 2>&1 && {
    [ $exit_code -eq 0 ] && notify-send "背景设置成功" "已将以下图片设为背景：\n$SELECTED_IMAGE" || notify-send "背景设置失败" "设置图片时出现错误：\n$SELECTED_IMAGE"
}

exit $exit_code